package parser;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;

import java.io.IOException;

/**
 * @Author:石小俊
 * @Date: 2022/12/26 14:18
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class DigesterParser {

    public static void main(String[] args) {
        // 解析rule.xml,将XML元素与Java对象关联在一起,并返回解析器
        Digester digester = DigesterLoader.createDigester(DigesterParser.class.getClassLoader().getResource("parser/rule.xml"));

        // 准备一个空的对象交给解析器
        // 该对象将会作为解析时根标签所对应的Java对象
        ClassBean classBean = new ClassBean();
        // 将该对象交给解析器
        digester.push(classBean);

        try {
            System.out.println("解析前:"+classBean);
            // 开始解析,解析后会自动将解析解析存放到交给解析器的对象中
            digester.parse(DigesterParser.class.getClassLoader().getResourceAsStream("students.xml"));
            System.out.println("解析后:"+classBean);
            System.out.println("班级号:"+classBean.getNo());
            System.out.println("学号为1的学生姓名:"+classBean.findStudent("1").getName());
            System.out.println("学号为2的学生性别:"+classBean.findStudent("2").getGender());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

}
